// Felica 連携サンプルアプリ
// Programed by Kazuyuki Eguchi (http://eguchi.jp)

package jp.eguchi.android.egg.felica;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

import com.felicanetworks.mfc.Felica;


public class FelicaServiceConnection implements ServiceConnection
{

    private static final FelicaServiceConnection instance = new FelicaServiceConnection();

    private Context context = null;

    private Felica felica = null;

    private boolean connected = false;

    private FelicaServiceConnection()
    {
    };

    public static FelicaServiceConnection getInstance()
    {
        return instance;
    }

    public void setContext(Context context)
    {
        this.context = context;
    }

    public void connect()
    {
    	Log.d("test","connect");

        if (context == null)
        {
            return;
        }

        if (connected)
        {
            return;
        }

        Intent intent = new Intent();
        intent.setClass(context, Felica.class);
        
        if (!context.bindService(intent, this, Context.BIND_AUTO_CREATE))
        {
            return;
        }
    }

    public void disconnect()
    {
    	Log.d("test","disconnect");

        if (context == null)
        {
            return;
        }

        if (!connected)
        {
            return;
        }

        context.unbindService(this);

        connected = false;
    }

    public void onServiceConnected(ComponentName name, IBinder service)
    {
    	Log.d("test","onServiceConnected");
        
    	Felica felica = ((Felica.LocalBinder)service).getInstance();
        
    	instance.setFelica(felica);
        
    	connected = true;
    }

    public void onServiceDisconnected(ComponentName name)
    {
    	Log.d("test","onServiceDisconnected");

    	connected = false;
    }

    public void setFelica(Felica felica)
    {
    	Log.d("test","setFelica");

    	this.felica = felica;
    }

    public Felica getFelica()
    {
    	Log.d("test","getFelica");

    	return felica;
    }
}
